package com.ruoyi.web.controller.admin.workbench;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.IConstructionItemService;
import com.ruoyi.system.service.ContractService;
import com.ruoyi.system.service.ProjectService;
import com.ruoyi.system.service.ConstructionProjectService;
import com.ruoyi.system.dto.ProgressCountDTO;
import com.ruoyi.system.dto.ProjectStagePointDTO;
import com.ruoyi.system.dto.ProjectsChartsDTO;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * 个人工作台 - 事项维度
 */
@RestController
@RequestMapping("/admin/workbench")
public class WorkbenchController extends BaseController {

    @Resource
    private IConstructionItemService projectItemService;

    @Resource
    private ProjectService projectService;

    @Resource
    private ConstructionProjectService constructionProjectService;

    @Resource
    private ContractService contractService;

    /**
     * 今日待跟进事项
     * GET /admin/workbench/items/today
     */
    @GetMapping("/items/today")
    public AjaxResult today(@RequestParam(required = false) Long projectId,
                            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate today) {
        int size = projectItemService.listTodayPendingFollowUps(projectId, today).size();
        return success(size);
    }

    /**
     * 超期未跟进事项
     * GET /admin/workbench/items/overdue
     */
    @GetMapping("/items/overdue")
    public AjaxResult overdue(@RequestParam(required = false) Long projectId,
                              @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate today) {
        int size = projectItemService.listOverduePendingFollowUps(projectId, today).size();
        return success(size);
    }

    /**
     * 已签单未开工合同数
     * GET /admin/workbench/stats/signed-not-started
     */
    @GetMapping("/stats/signed-not-started")
    public AjaxResult countSignedNotStarted() {
        long count = projectService.countSignedButNotStarted();
        return success(count);
    }

    /**
     * 待签合同数
     * GET /admin/workbench/stats/pending-sign
     */
    @GetMapping("/stats/pending-sign")
    public AjaxResult countPendingSign() {
        long count = projectService.countPendingSign();
        return success(count);
    }

    /**
     * 项目维度：在建工地数（已开工未结项）
     * GET /admin/workbench/stats/under-construction
     */
    @GetMapping("/stats/under-construction")
    public AjaxResult countUnderConstruction() {
        long count = constructionProjectService.countUnderConstructionProjects();
        return success(count);
    }

    /**
     * 超期预警（默认7天，可通过days指定窗口）
     * GET /admin/workbench/items/warn?projectId=&today=yyyy-MM-dd&days=7
     */
    @GetMapping("/items/warn")
    public AjaxResult warn(@RequestParam(required = false) Long projectId,
                           @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate today,
                           @RequestParam(required = false, defaultValue = "7") Integer days) {
        int size = projectItemService.listDueSoonPendingFollowUps(projectId, today, days).size();
        return success(size);
    }

    /**
     * 项目维度：已完工项目数
     * GET /admin/workbench/stats/finished
     */
    @GetMapping("/stats/finished")
    public AjaxResult countFinished() {
        long count = projectService.countFinishedProjects();
        return success(count);
    }

    /**
     * 项目维度：已开工项目数
     * GET /admin/workbench/stats/started
     */
    @GetMapping("/stats/started")
    public AjaxResult countStarted() {
        long count = projectService.countStartedProjects();
        return success(count);
    }

    /**
     * 合同客户数（签过合同且审核通过的项目客户数）
     * GET /admin/workbench/stats/contract-customers
     */
    @GetMapping("/stats/contract-customers")
    public AjaxResult countContractCustomers() {
        long count = contractService.countApprovedContractCustomers();
        return success(count);
    }

    /**
     * 项目动态列表（分页）
     * GET /admin/workbench/projects/dynamics?pageNum=&pageSize=&keyword=
     */
    @GetMapping("/projects/dynamics")
    public AjaxResult projectDynamics(@RequestParam(defaultValue = "1") int pageNum,
                                      @RequestParam(defaultValue = "10") int pageSize,
                                      @RequestParam(required = false) String keyword) {
        return success(projectService.queryProjectDynamics(pageNum, pageSize, keyword));
    }

    

    /**
     * 日历：当月每日待办数量汇总
     * GET /admin/workbench/calendar/summary?month=2025-09-01
     */
    @GetMapping("/calendar/summary")
    public AjaxResult calendarSummary(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate month) {
        if (SecurityUtils.hasRole("ADMIN") || SecurityUtils.hasRole("ROLE_ADMIN")) {
            // 管理员：统计每天签单（审核通过合同）的项目数量（对项目去重）
            return success(contractService.approvedSignedProjectsDaily(month));
        }
        // 设计师：沿用原有逻辑（当月未完成事项与日期区间有交集的数量汇总）
        return success(projectItemService.calendarSummary(month));
    }

    /**
     * 日历：指定日期的待办事项列表
     * GET /admin/workbench/calendar/todos?date=2025-09-12&projectId=
     */
    @GetMapping("/calendar/todos")
    public AjaxResult calendarTodos(@RequestParam
                                    @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date,
                                    @RequestParam(required = false) Long projectId) {
        if (SecurityUtils.hasRole("ADMIN") || SecurityUtils.hasRole("ROLE_ADMIN")) {
            // 管理员：返回指定日期的签单项目列表
            return success(contractService.approvedSignedProjectsByDate(date));
        }
        // 设计师：原逻辑（按事项过滤）
        return success(projectItemService.calendarTodos(date, projectId));
    }

    

    /**
     * 合并图表接口
     * GET /admin/workbench/projects/charts?keyword=
     * 响应：stagePoints（散点图数据）+ progressCounts（柱状图数据）
     */
    @GetMapping("/projects/charts")
    public AjaxResult charts() {
        List<ProjectStagePointDTO> stagePoints = projectService.listCurrentProjectStages();
        List<ProgressCountDTO> progressCounts = projectService.countProjectsByProgress();
        ProjectsChartsDTO dto = new ProjectsChartsDTO();
        dto.setStagePoints(stagePoints);
        dto.setProgressCounts(progressCounts);
        return success(dto);
    }
}


